package com.lightjet.macross.base.upms.repository;

import com.lightjet.macross.base.upms.domain.RoleInfo;
import com.lightjet.macross.base.upms.domain.RoleUserLink;
import com.lightjet.macross.base.upms.domain.SystemInfo;
import com.lightjet.macross.common.core.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository("roleUserMapRepository")
public interface RoleUserLinkRepository extends BaseRepository<RoleUserLink, Integer> {

    /** description:根据角色信息获取角色和用户关系  */
    List<RoleUserLink> findByRoleinfo(RoleInfo roleInfo);

    List<RoleUserLink> findByRoleinfo_BelongsystemAndUserkey(SystemInfo systemInfo, String userkey);

    @Query("select t.roleinfo from RoleUserLink t right join t.roleinfo  where t.roleinfo.belongsystem = :systeminfo and (t.userkey = :userkey or lower(t.roleinfo.roledescription) = 'anybody' )")
    List<RoleInfo> findBySystemAndUserWithAnybody(@Param("systeminfo")SystemInfo systeminfo, @Param("userkey")String userkey);


    @Query(value = "select e.* from r_roleuser t " +
            "left outer join roleinfo r on r.id = t.roleid " +
            "left outer join systeminfo s on s.id = r.systemid " +
            "left outer join ppm802_v_emps e on e.id = t.userkey " +
            "left outer join ppm802_v_dept d on d.ORDERID = e.orgid " +
            "where s.shotname = :ssname and (upper(r.roledescription)= :rolecode or :rolecode = '*') and (r.rolename = :rolename or :rolename = '*' ) " +
            "and (e.orgid = :deptid or -1 = :deptid)",nativeQuery = true)
    List<Map> findBySystemAndDeptAndRole(@Param("ssname") String ssname,@Param("deptid") Integer deptid,@Param("rolecode") String rolecode,@Param("rolename") String rolename);

    @Query("select t.roleinfo from RoleUserLink t where t.roleinfo.belongsystem.shortname = :systemshortname and t.userkey = :userkey ")
    List<RoleInfo> findBySystemShorNameAndUserKey(@Param("systemshortname") String systemshortname,@Param("userkey") String userkey);

    @Modifying
    @Query("delete from RoleUserLink t where t.roleinfo = :role and t.userkey = :userkey")
    void deleteByRoleAdUserkey(@Param("role") RoleInfo role,@Param("userkey") String userkey);
}
